<template>
  <div class="cc-tree">
    <el-tree :data="tData" :props="defaultProps" :accordion="false" @node-expand="expand" @node-collapse="collapse" :default-expanded-keys="expandedKey" :node-key="defaultProps.id" :expand-on-click-node="true" :render-content="renderContent">
    </el-tree>
  </div>
</template>

<script>

import map from "lodash/map"
import indexOf from "lodash/map"
import cloneDeep from "lodash/map"

export default {
  name: "ccTree",
  props: {
    treeData: Array,
    treeProps: Object
  },
  data() {
    return {
      expandedKey: [],
      defaultProps: {
        children: 'children',
        id: "Id",
        label: 'label'
      },
      tData: []
    }
  },
  watch: {
    treeData() {
      this.expandedKey = [];
      extend(this.defaultProps, this.treeProps);
      this.tData = cloneDeep(this.treeData);
    }
  },

  methods: {
    expand(data) {
      this.expandedKey.push(data[this.defaultProps.id]);
    },
    collapse(data) {
      const index = findIndex(this.expandedKey, (item) => {
        return data[this.defaultProps.id] == item[this.defaultProps.id];
      });
      this.expandedKey.splice(index, 1);
    },
    move(node, data, store, e, direction) {
      e.cancelBubble = true;
      let currentId = data[this.defaultProps.id],
        parent = node.parent,
        siblingsData = parent.getChildren() || store.root.data,
        currentIndex = findIndex(siblingsData, (item) => {
          return item[this.defaultProps.id] == currentId;
        });
      let id = data[this.defaultProps.id],
        label = data[this.defaultProps.label],
        children = data[this.defaultProps.children];

      const itemData = {};
      itemData[this.defaultProps.id] = id;
      itemData[this.defaultProps.label] = label;
      itemData[this.defaultProps.children] = children;

      if (direction == "up") {
        siblingsData.splice(currentIndex - 1, 0, itemData);
        siblingsData.splice(currentIndex + 1, 1);
      } else if (direction == "down") {
        siblingsData.splice(currentIndex + 2, 0, itemData);
        siblingsData.splice(currentIndex, 1);
      }
      setTimeout(() => {
        this.$emit("move", this.tData);
      }, 10);
    },

    renderContent(h, { node, data, store }) {
      return (
        <span>
          <span>
            <span>{node.label}</span>
          </span>
          <span class="move-action">
            <el-button size="mini" on-click={(event) => { this.move(node, data, store, event, "up") }} type="text">上移</el-button>
            <el-button size="mini" on-click={(event) => { this.move(node, data, store, event, "down") }} type="text">下移</el-button>
          </span>
        </span>);
    }
  },
  mounted() {
    return false;

  }
}
</script>

<style lang="less" scope>
@import "./index.less";
</style>
<style lang="less">
@import "./index.rw.less";
</style>

